﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Security;

namespace ProjectSem3.Admin
{
    public partial class WebForm9 : System.Web.UI.Page
    {

        private dataDataContext dc = new dataDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlSupplier.DataSource = dc.Suppliers.ToList();
                ddlSupplier.DataTextField = "Name";
                ddlSupplier.DataValueField = "SupplierID";
                ddlSupplier.DataBind();

                ddlCategory.DataSource = dc.Categories.ToList();
                ddlCategory.DataTextField = "Name";
                ddlCategory.DataValueField = "CategoryID";
                ddlCategory.DataBind();

                if (Request.QueryString["id"] != null)
                {
                    Product Pr = this.dc.Products.Single(c => c.ProductID == Convert.ToInt32(Convert.ToString(Request.QueryString["id"])));
                    this.TextBoxName.Text = Pr.Name;
                    this.TextBoxPrice.Text = Convert.ToDouble(Pr.Price).ToString();
                    this.TextBoxWarranty.Text = Convert.ToInt32(Pr.Warranty).ToString();
                    LabelView.Text = Pr.View == null ? "0" : Pr.View.Value.ToString();
                    this.TextArea1Des.InnerText = Pr.Description;
                    if (Pr.Status == true)
                    {
                        Radio1.Checked = true;
                    }
                    else Radio2.Checked = true;
                    foreach (ListItem item in ddlSupplier.Items)
                    {
                        if (Pr.Supplier.Name == item.Text)
                        {
                            ddlSupplier.SelectedIndex = ddlSupplier.Items.IndexOf(item); break;
                        }
                    }
                    foreach (ListItem item in ddlCategory.Items)
                    {
                        if (Pr.Category.Name == item.Text)
                        {
                            ddlCategory.SelectedIndex = ddlCategory.Items.IndexOf(item); break;
                        }
                    }
                    loadIMGS(Pr);
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["ID"] != null)
            {
                try
                {
                    Product Pro = dc.Products.Single(Prod => Prod.ProductID == Convert.ToInt32(Request.QueryString["ID"]));
                   
                    
                        if (checkImg(fileImg1, lblFile1) && checkImg(fileImg2, lblFile2) && checkImg(fileImg3, lblFile3))
                        {
                            insertIMG(fileImg1, lblFile1, Pro.ProductID, hdfImgID2.Value);
                            insertIMG(fileImg2, lblFile2, Pro.ProductID, hdfImgID2.Value);
                            insertIMG(fileImg3, lblFile3, Pro.ProductID, hdfImgID3.Value);
                            Pro.SupplierID = Convert.ToInt32(this.ddlSupplier.SelectedValue);
                            Pro.CategoryID = Convert.ToInt32(this.ddlCategory.SelectedValue);
                            Pro.Name = this.TextBoxName.Text;
                            Pro.Price = Convert.ToDouble(this.TextBoxPrice.Text);
                            Pro.Warranty = Convert.ToInt32(this.TextBoxWarranty.Text);
                            Pro.Status = Radio1.Checked ? Radio1.Checked : false;
                            Pro.DateUpdate = DateTime.Now;
                            Pro.Description = this.TextArea1Des.InnerText;

                            this.dc.SubmitChanges();

                            Response.Redirect("ListProduct.aspx",false);
                        }
                    
                }
                catch (Exception ex)
                {
                   
                   Response.Redirect("Default.aspx");
                }

            }
        }

        private bool checkImg(FileUpload file, Label lbl)
        {
            if (file.HasFile)
            {
                if (file.PostedFile.ContentType == "image/jpeg" || file.PostedFile.ContentType == "image/png" || file.PostedFile.ContentType == "image/gif")
                {
                    if (file.PostedFile.ContentLength < (102400 * 3))
                    {
                       
                        return true;
                    }
                    else
                    {
                        lbl.Text = "The file has to be less than 300 kb!";
                        return false;
                    }
                }
                else
                {
                    lbl.Text = " upload *.jpeg,*.png,*.gif,*.jpg file!";
                    return false;
                }
            }
            return true;
        }
        private void insertIMG(FileUpload file, Label lbl, int proid, string imgid)
        {
            try
            {
                if (file.HasFile)
                {
                    string filename = Path.GetFileName(file.FileName);
                    string[] arrfilename = filename.Split('.');
                    string tag = arrfilename[arrfilename.Length - 1];

                    filename = FormsAuthentication.HashPasswordForStoringInConfigFile(filename + DateTime.Now + new Random().Next(0, 10000), "sha1") + tag;
                    file.SaveAs(Server.MapPath(@"~/images/Product/") + filename);

                    //insert images to db
                    if (String.IsNullOrEmpty(imgid))
                    {
                        ImagesPro img = new ImagesPro();
                        img.ProductID = proid;
                        img.NameImg = filename;
                        dc.ImagesPros.InsertOnSubmit(img);
                        dc.SubmitChanges();
                    }
                    else
                    {
                        ImagesPro img = dc.ImagesPros.Single(d => d.IDImg == Convert.ToInt32(imgid));
                        DeleteFile("~/images/Product/"+img.NameImg);
                        img.NameImg = filename;
                        dc.SubmitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                lbl.Text = "The file could not be uploaded. The following error occured: " + ex.Message;

            }
        }
        //Delete File
        private void DeleteFile(string fileName)
        {
            try
            {
                FileInfo fi;
                if (System.IO.File.Exists(fileName) == true)
                {
                    fi = new FileInfo(fileName);
                    fi.Delete();
                }
            }
            catch (Exception ex) { ex.Message.ToString(); }
        }

        //load images
        private void loadIMGS(Product pr)
        {

            List<ImagesPro> listImg = pr.ImagesPros.ToList();
            for (int i = 0; i < listImg.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        spImg1.InnerHtml = " <img src='../images/Product/" + listImg[i].NameImg + "' alt='' width='45px' height='50px' /> &nbsp;&nbsp;&nbsp; ";
                        hdfImgID1.Value = listImg[i].IDImg.ToString();
                        break;
                    case 1:
                        spImg2.InnerHtml = " <img src='../images/Product/" + listImg[i].NameImg + "' alt='' width='45px' height='50px' /> &nbsp;&nbsp;&nbsp; ";
                        hdfImgID2.Value = listImg[i].IDImg.ToString();
                        break;
                    default:
                        spImg3.InnerHtml = " <img src='../images/Product/" + listImg[i].NameImg + "' alt='' width='45px' height='50px' /> &nbsp;&nbsp;&nbsp; ";
                        hdfImgID3.Value = listImg[i].IDImg.ToString();
                        break;
                }
            }
        }

    }
}